from KThread import KThread as kthread
from time import sleep
from commands import getoutput
from os import system, linesep, getlogin, sep as os_sep
from os.path import realpath, expandvars, split as path_split
import gtk
import pango
import gtk.glade
import gobject

def _(txt):
    return txt
    
def setbw_(reference):
    global _
    _ = reference

def setbwT(reference):
    global T
    T = reference

class DownloadWindow(object):
    def __init__(self,tree,parent):
        self.me = tree
        self.tree = self.me.get_widget("downloadingtreeview")
        self.window = self.me.get_widget("downloadingdialog")
        dict = {"on_button7_clicked" : self.__clearfinished,
                "on_downloadingdialog_delete_event" : self.__destroyevent,
                "on_downloadingdialog_response" : self.__response,
                "on_downloadingtreeview_button_press_event" : self.__listbtn,
                "on_menuitem16_activate" : self.__restartdownload,
                "on_menuitem12_activate" : self.__stopdownload,
                "on_menuitem14_activate" : self.__opendownload,
                "on_menuitem15_activate" : self.__gotodownloadfolder,
                
        }
        self.me.signal_autoconnect(dict)
        self.parent = parent
        self.controlthread = None
        self.__initialize()
    
    def __restartdownload(self,*args):
        widget = self.me.get_widget("downloadingtreeview")
        items = widget.get_selection().get_selected_rows()[1]
        model = widget.get_model()
        for i in items:
            model[i[0]][4] = model[i[0]][7]
            if model[i[0]][7]==-1:
                info = _("downloaddownloading")
            else:
                info = None
            model[i[0]][5] = info
            model[i[0]][3].restart()
        self.__controller()
    
    def __stopdownload(self,*args):
        widget = self.me.get_widget("downloadingtreeview")
        items = widget.get_selection().get_selected_rows()[1]
        model = widget.get_model()
        for i in items:
            model[i[0]][3].cancel()
            
    def __opendownload(self,*args):
        widget = self.me.get_widget("downloadingtreeview")
        items = widget.get_selection().get_selected_rows()[1]
        model = widget.get_model()
        for i in items:
            system("xdg-open "+model[i[0]][3].localpath)
            
    def __gotodownloadfolder(self,*args):
        widget = self.me.get_widget("downloadingtreeview")
        items = widget.get_selection().get_selected_rows()[1]
        model = widget.get_model()
        for i in items:
            system("xdg-open "+path_split(model[i[0]][3].localpath)[0])
        
    def __listbtn(self,widget,event):
        if event.button == 3:
            x = int(event.x)
            y = int(event.y)
            time = event.time
            pthinfo = widget.get_path_at_pos(x, y)
            if pthinfo == None:
                widget.get_selection().unselect_all()
            else:
                pthinfo = pthinfo[0]
                items = widget.get_selection().get_selected_rows()[1]
                if not pthinfo in items:
                    widget.get_selection().unselect_all()
                    widget.get_selection().select_path(pthinfo)
                    widget.set_cursor(pthinfo)
            row = widget.get_model()[pthinfo[0]]
            boola = row[2] != 100 and row[4] != -1
            self.me.get_widget("menuitem12").set_property("visible",boola)
            self.me.get_widget("menuitem16").set_property("visible",not boola)
            self.me.get_widget("menuitem14").set_property("sensitive", row[2]==100)
            self.me.get_widget("menu6").popup( None, None, None, event.button, time)
            return True
        elif widget.get_path_at_pos(int(event.x), int(event.y))==None:
            widget.get_selection().unselect_all()
            return True
    
    def __clearfinished(self,*args):
        model = self.tree.get_model()
        for i in model:
            if i[2]==100 or i[4] == -1:
                model.remove(i.iter)
    
    def __response(self,widget,id):
        if id == 0:
            self.hide()
    
    def hide(self):
        self.window.hide()
        
    def show(self):
        self.window.set_title(_("downloadprogresswindow"))
        self.me.get_widget("label34").set_label(_("clearstoped"))
        self.window.show()
        
    def __destroyevent(self):
        self.window.hide()
        return True
        
    def __initialize(self):
        widget = self.tree
        widget.set_headers_visible(False)
        model = widget.get_model()
        if model!=None:
            model.clear()
            
        model = gtk.ListStore(  gtk.gdk.Pixbuf,
                                gobject.TYPE_STRING,
                                gobject.TYPE_INT,
                                object,
                                gobject.TYPE_INT,
                                gobject.TYPE_STRING,
                                gobject.TYPE_INT,
                                gobject.TYPE_INT,
                                )
        
        column = gtk.TreeViewColumn()
        render1 = gtk.CellRendererPixbuf()
        column.pack_start(render1, expand=False)
        column.add_attribute(render1, 'pixbuf', 0)
        widget.append_column(column)
        
        column = gtk.TreeViewColumn()
        render2 = gtk.CellRendererText()
        column.pack_start(render2, expand=True)
        column.add_attribute(render2, 'text', 1)
        render2.set_property("ellipsize", pango.ELLIPSIZE_START)
        column.set_resizable(True)
        column.set_expand(True)
        widget.append_column(column)
        
        column = gtk.TreeViewColumn()
        render3 = gtk.CellRendererProgress()
        column.pack_start(render3, expand=False)
        column.add_attribute(render3, "value", 2)
        column.add_attribute(render3, "text", 5)
        column.add_attribute(render3, "pulse", 6)
        render3.set_fixed_size(200,-1)
        widget.append_column(column)
        
        widget.set_model(model)
    
    def download(self,rows=[],path=expandvars("$HOME")):
        #model2.append([pixbuf,name,path,format,line[5],line[6]+" "+line[7],None,None])
        model = self.tree.get_model()
        #Sustitutive workaround: char alternatives
        #The sustitutive is a workaround for "filename[ ]" sftp bug.
        self.sustitutives = ["_","%","=","+","*"]
        commands_delayed = []
        fileinfo = []
        for i in rows:
            remotepath = i[2]
            localpath = path + ("/"*int(not path[-1]=="/")) + path_split(i[2])[1]
            # Sustitutive workaround: 1st renaming
            sustitutive = None
            '''
            if "[" in remotepath:
                for j in self.sustitutives:
                    if j not in remotepath:
                        oldremotepath = remotepath
                        remotepath = remotepath.replace("[",j)
                        commands_delayed.append("mv \"" +oldremotepath+ "\" \"" +remotepath +"\"")                            
                        sustitutive = j
                        break
            '''
            size = -1
            if i[3]!="directory":
                try:
                    size = int(i[4])
                except:
                    pass
            else:
                size = 0
            
            if len(remotepath)>1 and remotepath[-1]=="/":
                remotepath = remotepath[:-1]
            if len(localpath)>1 and localpath[-1]==os_sep:
                remotepath = remotepath[:-1]
            
            fileinfo.append((i[0],remotepath,localpath,i[3],size,sustitutive))

        if len(commands_delayed)>0:
            self.parent.worksection(True)
            self.parent.c.exec_commands_with_session(
                commands_delayed,
                self.parent.c.auxsession)
            self.parent.worksection(False)            
    
        for i in fileinfo:
            #instance = T.scpinstance(T.ip,T.user,T.passw,T.port,,localdir=path)
            instance = T.scpinstance(ip=T.ip, user=T.user, passw=T.passw, 
                 port=T.port,sustitutive=i[5],mimetype=i[3],remotepath=i[1],localpath=i[2])
            info = None
            if i[4]==-1:
                info = _("downloaddownloading")
            model.append([i[0],i[1],0,instance,i[4],info,-1,i[4]])
        
        self.__controller()
        self.show()
        return
        
    def __controller(self,ufo=False):
        if ufo:
            model = self.tree.get_model()
            k = 0
            self.me.get_widget("downloadinglabel").set_label(_("scpdownloading"))
            while k < 1:
                gtk.gdk.threads_enter()
                calc = 0
                for i in model:
                    if i[2] != 100 and i[4] != -1:
                        salida = -1
                        if i[4] != 0:
                            try:
                                salida = int(getoutput("stat --format=\"%s\" \""+i[3].localpath+"\""))
                            except:
                                print "Stat error looking for "+i[3].localpath+" file."
                        else:
                            salida = 0
                        
                        if not i[3].isalive():
                            if i[3].usercancel:
                                i[4] = -1
                                i[5] = _("downloadcanceled")
                            else:
                                if salida<i[4]:
                                    # or i[3].exitstatus()[1]!=None
                                    i[4] = -1
                                    i[5] = _("downloadinterrupted")
                                else:
                                    i[6] = -1
                                    i[2] = 100
                                    i[5] = _("downloadfinished")
                            # Look for sftp bug
                            # Sustitutive workaround: 2nd renaming
                            if i[3].sustitutive != None:
                                original = i[3].filepath.replace(i[3].sustitutive,"[")
                                self.parent.worksection(True)
                                response = self.parent.c.exec_commands_with_session(
                                        ["mv \""+i[3].remotepath+"\" \""+original+"\""],
                                        self.parent.c.auxsession)
                                self.parent.worksection(False)
                        elif salida == 0:
                            i[6] = i[6] + 1 + int(i[6]<0)
                        else:
                            i[2] = int((salida/float(i[4]))*100)
                        
                    calc += i[2]
                k = calc/float(100*len(model))
                self.me.get_widget("downloadingbar").set_fraction(k)
                gtk.gdk.threads_leave()
                sleep(1)
            gtk.gdk.threads_enter()
            self.me.get_widget("downloadinglabel").set_label(_("scpfinished"))
            self.me.get_widget("downloadingbar").set_fraction(1.)
            gtk.gdk.threads_leave()
            self.controlthread = None
        elif self.controlthread==None:
            self.controlthread = kthread(target=self.__controller,kwargs={"ufo":True,})
            self.controlthread.start()
    
            
class BrowseWindow(object):
    def __init__(self,tree,parent,connection):
        self.me = tree
        self.parent = parent
        self.c = connection
        self.d = DownloadWindow(tree,self)
        self.location = None
        dict = {"on_menuitem10_activate" : self.__downfiles,
                "on_locationentry_changed" : self.__locationchanged,
                "on_browsedialog_delete_event" : self.__destroyevent,
                "on_browsedialog_response" : self.__response,
                "on_iconview_button_press_event" : self.__iconviewbtn,
                "on_browseview_button_press_event" : self.__browseviewbtn,
                "on_combobox5_changed" : self.__ordercomboboxchanged,
                "on_combobox6_changed" : self.__ordercomboboxchanged,
                "on_button8_clicked" : self.__showdownloads,
                "on_menuitem11_activate" : self.__fileprop,
                "on_fileinfo_delete_event" : self.__filepropclose,
                "on_fileinfo_response" : self.__filepropclose,
                "on_browsedialog_focus_in_event" : self.__window_twink_end,
                "on_menuitem13_activate" : self.__removedialog,
                "on_menuitem17_activate" : self.__cut,
                "on_menuitem18_activate" : self.__copy,
                "on_menuitem19_activate" : self.__paste,
                }
        self.me.signal_autoconnect(dict)
        self.posibilities = []
        self.syntetic     = []
        self.iconsize1 = gtk.ICON_SIZE_DIALOG
        self.iconsize2 = gtk.ICON_SIZE_BUTTON
        self.icon_folder   = self.me.get_widget("browsedialog").render_icon(gtk.STOCK_DIRECTORY, self.iconsize1)
        self.icon_file     = self.me.get_widget("browsedialog").render_icon(gtk.STOCK_FILE, self.iconsize1)
        self.icon_media    = self.me.get_widget("browsedialog").render_icon("gtk-harddisk", self.iconsize2)
        self.icon_folder_b = self.me.get_widget("browsedialog").render_icon(gtk.STOCK_DIRECTORY, self.iconsize2)
        self.icon_up       = self.me.get_widget("browsedialog").render_icon("gtk-go-up", self.iconsize2)
        self.icon_home     = self.me.get_widget("browsedialog").render_icon(gtk.STOCK_HOME, self.iconsize2)
        self.icontheme = gtk.icon_theme_get_default()
        self.__initialize()
        self.__internationalize()
        self.working = False
        self.kill = False
        
        self.mode = 0
        # 0 - Browse and download, 1 - select folder
        self.clipboard = []
        self.cut = False
        self.currentdir = []
        
        self.sortcolumn = -1
        self.sortorder = gtk.SORT_ASCENDING
        
        self.keepthread = kthread(target=self.keepalive)
        self.keepthread.start()
        
            
    def __removedialog(self,*args):
        dialog = gtk.MessageDialog(self.me.get_widget("browsedialog"),
            flags=gtk.DIALOG_MODAL, type=gtk.MESSAGE_QUESTION,
            buttons=gtk.BUTTONS_YES_NO, 
            message_format=_("removeconfirmation"))
        dialog.connect("response",self.__removedialogresponse)
        dialog.show()
        
    def __removedialogresponse(self,widget,response):
        if response==-8:
            filelist = []
            model = self.me.get_widget("iconview").get_model()
            for i in self.me.get_widget("iconview").get_selected_items():
                filelist.append(model[i[0]][2])
            self.__removefiles(filelist)
            self.__updateposibilities()
        widget.destroy()
    
    def __removefiles(self,filelist):
        txt = ""
        for i in filelist:
            txt += "\""+i+"\" "
        txt = txt[:int(len(txt)>0)*-1]
        self.__turnstart()
        returned = self.c.exec_commands_with_session(
                ["rm -r --interactive=never "+txt],
                self.c.auxsession)
        self.__turnend()
        
    def __copy(self,*args):
        tmp = []
        model = self.me.get_widget("iconview").get_model()
        for i in self.me.get_widget("iconview").get_selected_items():
            tmp.append(model[i[0]][2])
        if len(tmp)>0:
            self.cut = False
            self.clipboard = tmp
        
    def __cut(self,*args):
        tmp = []
        model = self.me.get_widget("iconview").get_model()
        for i in self.me.get_widget("iconview").get_selected_items():
            if model[i[0]][6]==T.user:
                tmp.append(model[i[0]][2])
        if len(tmp)>0:
            self.cut = True
            self.clipboard = tmp
        
    def __paste(self,*args):
        destination = None
        items =  self.me.get_widget("iconview").get_selected_items()
        if len(items)==0 and self.currentdir[3]==T.user:
            destination = self.location
        elif len(items)==1:
            row = self.me.get_widget("iconview").get_model()[items[0][0]]
            if row[6]==T.user:
                destination = row[3]
        if destination != None and len(self.clipboard)>0:
            files = ""
            for i in self.clipboard:
                files += "\"%s\" " % i
            command = "cp -r "
            if self.cut:
                command = "mv "
                self.clipboard = []
            command += files +" --target-directory="+self.location
            self.__turnstart()
            self.c.exec_commands_with_session([command],self.c.auxsession) 
            self.__turnend()
            self.__updateposibilities()
        
    def __window_twink_end(self,*args):
        if self.me.get_widget("browsedialog").get_urgency_hint():
            self.me.get_widget("browsedialog").set_urgency_hint(False)
        
    def __fileprop(self,*args):
        widget = self.me.get_widget("iconview")
        items = widget.get_selected_items()
        if len(items)==1:
            row = widget.get_model()[items[0]]
            #model2.append([pixbuf,name,path,format,line[5],line[6]+" "+line[7],None,None])
            try:
                size = ""
                tmp = int(row[4])
                for i in ("Bytes","KBytes","MBytes","GBytes","TBytes","PBytes"):
                    if int(tmp)/1024 > 0:
                        tmp = tmp/1024.
                    else:
                        size = "%d.%d %s" % (int(tmp),(tmp*100)-(int(tmp)*100),i)
                        break
            except:
                size = "Unknown"
                
            self.me.get_widget("fileinfo").set_title(_("fileinfotitle"))
            for x, y in (("label35",_("fileinfoname")),
                         ("label38",_("fileinfomime")),
                         ("label40",_("fileinfodate")),
                         ("label41",_("fileinfosize")),
                         ("label43",_("fileinfousername")),
                         ("label44",_("fileinfousergroup"))):
                self.me.get_widget(x).set_label(y)
                
            for x, y in (("label36",row[1]),
                          ("label39",row[3]),
                          ("label37",row[5]),
                          ("label42",size),
                          ("label45",row[6]),
                          ("label46",row[7])):
                self.me.get_widget(x).set_label(y)
            self.me.get_widget("fileinfo").set_property("visible",True)
        
    def __filepropclose(self,*args):
        self.me.get_widget("fileinfo").set_property("visible",False)
        return True
        
    def __showdownloads(self,*args):
        self.d.show()
        
    def __downfiles(self,*args):
        selector = gtk.FileChooserDialog(title=_("downloadfolderselector"),
                                         parent=self.me.get_widget("window1"),
                                         action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                                         buttons=(gtk.STOCK_CANCEL,0,gtk.STOCK_SAVE,1), backend=None)
        selector.set_local_only(True)
        selector.set_select_multiple(False)
        selector.connect("response",self.__seleccionado)
        selector.show()

    def __seleccionado(self,widgetb,id):
        widgetb.hide()
        if id:
            path = realpath(widgetb.get_filename())
            rows = []
            widget = self.me.get_widget("iconview")
            model = widget.get_model()
            for i in widget.get_selected_items():
                rows.append(model[i[0]])
            self.d.download(rows,path)
        widgetb.destroy()
        
    def __ordercomboboxchanged(self,*args):
        self.orderby()
            
    def go_home(self):
        self.__turnstart()
        returned = self.c.exec_commands_with_session(
                ["echo $HOME"],
                self.c.auxsession)
        self.__turnend()
        if returned!=None:
            homedir = returned[0].strip()
            self.go(path)
            
    def go(self,path):
        if self.location!=path:
            self.me.get_widget("locationentry").set_text(path)
            self.__updateposibilities()
                    
    def orderby(self):
        for i in ("combobox5","combobox6"):
            widget = self.me.get_widget(i)
            if widget.get_active()==-1:
                widget.set_active(0)
                return False
        
        self.sortcolumn = self.me.get_widget("combobox5").get_model()[self.me.get_widget("combobox5").get_active()][0]
        self.sortorder = self.me.get_widget("combobox6").get_model()[self.me.get_widget("combobox6").get_active()][0]
        
        self.me.get_widget("iconview").get_model().set_sort_column_id(self.sortcolumn,self.sortorder)
        return True
        
    def keepalive(self):
        while not self.kill:
            while self.c.auxsession == None and not self.kill:
                sleep(0.2)
            timeout = self.parent.options.getint("DEFAULT","sshalive")
            if timeout == 0 or self.c.protocol==0:
                sleep(5)
            else:
                self.__turnstart()
                self.c.exec_commands_with_session(["echo 1"],self.c.auxsession)
                self.__turnend()
                sleep(timeout/1000.)
            
    def __turnstart(self):
        while self.working:
            sleep(0.1)
        self.working = True
        
    def __turnend(self):
        self.working = False
    
    def worksection(self,value=True):
        if value:
            self.__turnstart()
        else:
            self.__turnend()
                    
    def __iconviewbtn(self,widget,event):
        deselect = False
        if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
            x = int(event.x)
            y = int(event.y)
            time = event.time
            pthinfo = widget.get_path_at_pos(x, y)
            if pthinfo == None:
                widget.unselect_all()
            else:
                type = widget.get_model()[pthinfo][3]
                loc = widget.get_model()[pthinfo][2] 
                if type == "directory":
                    self.me.get_widget("locationentry").set_text(loc)
            return True
        elif event.button == 3 and self.mode==0:
            x = int(event.x)
            y = int(event.y)
            time = event.time
            pthinfo = widget.get_path_at_pos(x, y)
            items = []
            own = False
            pasteable = False
            if pthinfo == None:
                widget.unselect_all()
                pasteable = T.user==self.currentdir[3]
            else:
                items = widget.get_selected_items()
                if not pthinfo in items:
                    widget.unselect_all()
                    widget.select_path(pthinfo)
                    widget.set_cursor(pthinfo)
                    items = [widget.get_item_at_pos(x,y)[0]]
                
                model = widget.get_model()
                own = True
                for i in items:
                    if model[i[0]][6] != T.user:
                        own = False
                        break

                pasteable = len(items)==1 and model[items[0][0]][6]==T.user and model[items[0][0]][3]=="directory"
                
            self.me.get_widget("menuitem11").set_property("sensitive",len(items)==1)
            self.me.get_widget("menuitem13").set_property("sensitive",own and len(items)>0)
            self.me.get_widget("menuitem17").set_property("sensitive",own and len(items)>0)
            self.me.get_widget("menuitem18").set_property("sensitive",len(items)>0)
            self.me.get_widget("menuitem19").set_property("sensitive",pasteable and self.clipboard)
            self.me.get_widget("menu5").popup( None, None, None, event.button, time)
            return True
        elif widget.get_path_at_pos(int(event.x), int(event.y))==None:
            widget.unselect_all()
            return True
            
    def __browseviewbtn(self,widget,event):
        deselect = False
        if event.button == 1:
            # and event.type == gtk.gdk._2BUTTON_PRESS:
            x = int(event.x)
            y = int(event.y)
            time = event.time
            pthinfo = widget.get_path_at_pos(x, y)
            if pthinfo == None:
                widget.get_selection().unselect_all()
            else:
                row = widget.get_model()[pthinfo[0][0]]
                self.me.get_widget("locationentry").set_text(row[3])
            return True

        elif widget.get_path_at_pos(int(event.x), int(event.y))==None:
            widget.get_selection().unselect_all()
            return True
    
    def __internationalize(self):
        model = self.me.get_widget("combobox5").get_model()
        aux = (_("Obn"),_("Obt"),_("Obs"))
        for i in range(3):
            model[i][1] = aux[i]
            
        model = self.me.get_widget("combobox6").get_model()
        aux = (_("Asc"),_("Des"))
        for i in range(2):
            model[i][1] = aux[i]
            
    def itn(self):
        self.__internationalize()   
        
    def __rowsep(self,model, iter, data=None):
        return model[model.get_path(iter)[0]][2]
        
    def __initialize(self):
        for i in ("combobox5","combobox6"):
            widget = self.me.get_widget(i)
            
            if widget.get_model() != None:
                widget.get_model().clear()
            
            model = gtk.ListStore(  gobject.TYPE_INT,
                                    gobject.TYPE_STRING,
                                    )
            render = gtk.CellRendererText()
            
            widget.pack_start(render, expand=False)
            widget.add_attribute(render, 'text', 1)
            widget.set_model(model)
            
        model = self.me.get_widget("combobox5").get_model()
        for k,i in ((1,"Obn"),(5,"Obt"),(4,"Obs")):
            model.append([k,i])
            
        model = self.me.get_widget("combobox6").get_model()
        for k,i in ((gtk.SORT_ASCENDING,"Asc"),(gtk.SORT_DESCENDING,"Des")):
            model.append([k,i])
        
        widget = self.me.get_widget("iconview")
        model = gtk.ListStore(  gtk.gdk.Pixbuf,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                gobject.TYPE_STRING,
                                )
        widget.set_selection_mode(gtk.SELECTION_MULTIPLE)
        render = gtk.CellRendererPixbuf()
        widget.pack_start(render, expand=False)
        widget.add_attribute(render, 'pixbuf', 0)
        render = gtk.CellRendererText()
        widget.pack_start(render, expand=False)
        widget.add_attribute(render, 'text', 1)
        render.set_property("alignment", pango.ALIGN_CENTER)
        render.set_property("ellipsize", pango.ELLIPSIZE_END)
        render.set_fixed_size(60, -1)
        widget.set_model(model)
        widget.set_tooltip_column(1)
        
        widget = self.me.get_widget("browseview")
        widget.set_headers_visible(False)
                
        model = gtk.ListStore(  gtk.gdk.Pixbuf,
                                gobject.TYPE_STRING,
                                gobject.TYPE_BOOLEAN,
                                gobject.TYPE_STRING,
                                )
        
        column = gtk.TreeViewColumn()
        render1 = gtk.CellRendererPixbuf()
        column.pack_start(render1, expand=False)
        column.add_attribute(render1, 'pixbuf', 0)

        render2 = gtk.CellRendererText()
        column.pack_start(render2, expand=True)
        column.add_attribute(render2, 'text', 1)
        render2.set_property("ellipsize", pango.ELLIPSIZE_END)
        
        widget.append_column(column)
        widget.set_model(model)
        widget.set_row_separator_func(self.__rowsep)
        
    def __destroyevent(self,*args):
        self.hide()
        return True
        
    def __locationchanged(self,*args):
        location = self.me.get_widget("locationentry").get_text()
        if location=="/" or location in self.posibilities or location in self.syntetic:
            self.location = location
            self.__updateposibilities()
        elif location[-3:]=="/..":
            new = location[:location[:-3].rfind("/")]
            if len(new)==0:
                new = "/"
            if new in self.posibilities:
                self.me.get_widget("locationentry").set_text(new)
    
    def __response(self,widget,id):
        if id==1 and self.mode == 1:
            folder = ""
            items = self.me.get_widget("iconview").get_selected_items()
            nsel = len(items)
            if nsel in (0,1,):
                if nsel==0:
                    folder = self.me.get_widget("locationentry").get_text()
                else:
                    item = self.me.get_widget("iconview").get_model()[items[0]]
                    if item[3] == "directory":
                        folder = item[2]

            if len(folder)>0:
                self.parent.opsbrowseset(folder)
                self.hide()
        else:
            self.hide()
                
    def __updateposibilities(self):
        entrytext = self.me.get_widget("locationentry").get_text().strip()
        location = entrytext
        if len(location)>0:
            if location[-1]!="/":
                location += "/"
            self.__turnstart()
            commands = ["echo $HOME","df -hlTPx tmpfs","ls -1a \""+location+"\"","ls -las \""+location+"\"","file -pi "+location+"*"]
            returned = self.c.exec_commands_with_session(
                commands,
                self.c.auxsession)
            self.__turnend()
            model1 = self.me.get_widget("browseview").get_model()
            model2 = self.me.get_widget("iconview").get_model()
            for i in model1:
                model1.remove(i.iter)
            
            self.syntetic = []
            for i in returned[1].strip().split("\n")[1:]:
                if len(i.strip())==0:
                    continue
                line = i.split()
                model1.append([self.icon_media,line[-1],False,line[-1]])
                self.syntetic.append(line[-1])
            
            home = returned[0].strip()
            model1.append([self.icon_home,home,False,home])
            
            self.syntetic.append(home)
            
            model1.append([None,None,True,None])
            
            if location != "/":
                model1.append([self.icon_up,"..",False,location+".."])
                
            for i in model2:
                model2.remove(i.iter)
            
            if len(returned)==len(commands):
                lsnames = returned[2].strip()
                ls = returned[3].strip()
                
                filelines = {}
                fileout = returned[4].strip()
                for i in fileout.split(linesep):
                    filelines[i.split(":")[0].strip()] = i.split(":")[1].strip()
                
                
                
                self.posibilities = ["/"]
                aux = ""
                for i in location.split("/"):
                    i = i.strip()
                    if i and i not in self.posibilities:
                        aux += "/" + i
                        self.posibilities.append(aux)
                        self.posibilities.append(aux+"/")
                    
                lsaux = ls.split(linesep)[1:]
                lsnamesaux = lsnames.split(linesep)
                nls = (len(lsaux)*int(len(lsaux)==len(lsnamesaux)))
                self.me.get_widget("label26").set_text(_("nfile"+("s"*int(nls>1))).replace("$n",str(nls)))
                for pika in range(nls):
                    i = lsaux[pika]
                    k = lsnamesaux[pika]
                    if "ls:" in i and location+":" in i:
                        print "Error"
                        break
                    i = i.strip()
                    line = i.split()
                    name = k.strip()
                    if len(line)<9:
                        continue
                    elif line[-1] in (".",".."):
                        if line[-1]==".":
                            self.currentdir = line
                        continue
                    
                    path = location+name
                    if "->" in i:
                        aux = i[i.rfind("->"):].strip()
                        if aux[0]!="/":
                            path = location+aux
                    pixbuf = self.icon_file
                    format = "unknown"
                    if filelines.has_key(path):
                        format = filelines[path]

                    if line[1][0]=="d":
                        format = "directory"
                        self.posibilities.append(path)
                        self.posibilities.append(path+"/")
                        pixbuf = self.icon_folder
                        model1.append([self.icon_folder_b,name,False,path])
                    
                    model2.append([pixbuf,name,path,format,line[5],line[6]+" "+line[7],line[3],line[4]])
                    
            else:
                self.currentdir = [None]*8
                self.me.get_widget("label26").set_text(_("forbiddenfolder"))
                    
                    
            
            selection = self.me.get_widget("browseview").get_selection()
            for i in model1:
                if i[3]==entrytext and not selection.path_is_selected(i.path):
                    selection.select_path(i.path)
        else:
            self.me.get_widget("locationentry").set_text("/")        
        
    def show(self,style=0,path=None):
        self.mode = style
        self.me.get_widget("browsedialog").set_title(_("sshbrowser"))
        self.me.get_widget("button4").set_property("visible",style==1)
        self.me.get_widget("button5").set_property("visible",style==1)
        self.me.get_widget("button6").set_property("visible",style==0)
        if path!=None:
            self.go(path)
        elif self.location==None:            
            self.go_home()
        else:
            self.__updateposibilities()
        self.orderby()
        self.me.get_widget("browsedialog").set_property("visible",True)
        self.me.get_widget("browsedialog").set_urgency_hint(True)
        
    def checkfolder(self,path):
        self.__turnstart()
        if path[-1]!="/":
            path += "/"
        returned = self.c.exec_commands_with_session(
                ["ls "+path,"echo $?"],
                self.c.auxsession)
        self.__turnend()
        return (len(returned)==2 and returned[1]=="0")
        
    def hide(self):
        self.me.get_widget("browsedialog").set_property("visible",False)
